package com.weakteam.androidclient.data;

import android.app.Activity;
import android.util.Log;
import com.weakteam.androidclient.data.domain.Menu;
import com.weakteam.androidclient.util.MainProperties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.File;
import java.util.*;

/**
 * @author Nail
 */
public class ResourceData {

    private static ResourceData instance;

    private List<String> fileListQueue;

    private Activity activity;

    private boolean isMenuLoaded;
    private boolean isImagesLoaded;

    private ResourceDataEventHandler eventHandler;

    private float percent;
    private float percentStep;

    public void addResourceDataEventHandler(ResourceDataEventHandler handler) {
        this.eventHandler = handler;
    }

    private Map<Integer, Menu> menuMap;
    private List<Menu> menuList;


    public static ResourceData getInstance() {
        if (instance == null) instance = new ResourceData();
        return instance;
    }

    private ResourceData() {
        this.isMenuLoaded = false;
        this.isImagesLoaded = false;
    }

    public List<Menu> getMenuList() {
        return this.menuList;
    }

    public void load(Activity activity) {
        this.activity = activity;

        {
            DataRequest fileListRequest = new DataRequest(this.activity);
            String url = MainProperties.getInstance().getRootURL() + "getPriceData";
            fileListRequest.setURL(url);
            Log.i("android-client", "connect to " + url);
            fileListRequest.addTextResponse(new ITextResponse() {
                @Override
                public void onTextResponse(String text) {
                    Log.i("android-client", text);
                    ResourceData.this.menuListLoaded(text);
                }
            });
            fileListRequest.send();
        }


        {
            DataRequest fileListRequest = new DataRequest(this.activity);
            String url = MainProperties.getInstance().getRootURL() + "getPictureFileList";
            fileListRequest.setURL(url);
            Log.i("android-client", "connect to " + url);
            fileListRequest.addTextResponse(new ITextResponse() {
                @Override
                public void onTextResponse(String text) {
                    Log.i("android-client", text);
                    ResourceData.this.fileListLoaded(text);
                }
            });
            fileListRequest.send();
        }
    }

    private void fileListLoaded(String text) {

        this.percent += 0.05f;
        if (this.eventHandler != null) this.eventHandler.onLoadProgress(this.percent);

        if (text != null && text.length() > 0){
            try {
                JSONParser parser = new JSONParser();
                JSONArray jArray = (JSONArray)parser.parse(text);

                // check files

                this.fileListQueue = new LinkedList<String>();

                int n = jArray.size();

                for (int i = 0; i < n; i++) {
                    Object obj = jArray.get(i);
                    if (obj != null) {
                        String fileName = (String)obj;
                        this.fileListQueue.add(fileName);
                    }
                }

                if (n > 0) {
                    this.percentStep = 0.9f / (float)n;
                } else {
                    this.percentStep = 0.9f;
                }

                this.loadNextFile();

            } catch (ParseException ex) {
                Log.e("android-client", "fileListLoaded try to parse json" + ex);
            }
        }
    }

    private void loadNextFile() {
        if (this.fileListQueue.size() > 0) {
            String fileName = this.fileListQueue.get(0);
            this.fileListQueue.remove(0);

            DataRequest fileListRequest = new DataRequest(activity);
            String url = MainProperties.getInstance().getRootURL() + "getImage?name=" + fileName + "&mobile=false";
            fileListRequest.setURL(url);

            final File picturesFolder = MainProperties.getInstance().getPicturesFolder(this.activity.getApplicationContext());
            final File file = new File(picturesFolder, fileName);

            fileListRequest.addFileResponse(new IFileResponse() {
                @Override
                public void onFileResponse(File file) {
                    ResourceData.this.fileLoaded(file);
                }
            }, file);
            fileListRequest.send();
        } else {
            this.isImagesLoaded = true;
            this.loadCompleted();
        }
    }

    private void fileLoaded(File file) {
        Log.i("android-client", "fileLoaded " + file.getAbsolutePath());
        this.percent += this.percentStep;
        if (this.eventHandler != null) this.eventHandler.onLoadProgress(this.percent);
        this.loadNextFile();
    }

    private void loadCompleted() {
        if (this.isLoaded() && this.eventHandler != null) {
            this.eventHandler.onLoaded();
            this.eventHandler.onLoadProgress(1.0f);
        }
    }

    private boolean isLoaded() {
        return this.isMenuLoaded && this.isImagesLoaded;
    }


    private void menuListLoaded(String json) {
        this.percent += 0.05f;
        if (this.eventHandler != null) this.eventHandler.onLoadProgress(this.percent);

        try {
            JSONParser parser = new JSONParser();
            JSONArray jArray = (JSONArray)parser.parse(json);

            int n = jArray.size();

            this.menuMap = new HashMap<Integer, Menu>(n);
            this.menuList = new ArrayList<Menu>(n);

            for (int i = 0; i < n; i++) {
                JSONObject jMenu = (JSONObject)jArray.get(i);
                Menu menu = new Menu(jMenu);
                this.menuMap.put(menu.getId(), menu);
                this.menuList.add(menu);
            }

            this.isMenuLoaded = true;
            this.loadCompleted();
        } catch (ParseException ex) {
            Log.e(MainProperties.LOG_TAG, "menuListLoaded try to parse json" + ex);
        }
    }

}
